package com.hyfrogx.modules.app.controller.zoom;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hyfrogx.common.exception.MyException;
import com.hyfrogx.common.log.LogEnum;
import com.hyfrogx.common.log.LogUtils;
import com.hyfrogx.common.param.PayType;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.modules.app.annotation.Login;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.manage.entity.HyProductionScaleEntity;
import com.hyfrogx.modules.manage.entity.payrecord.HyPayRecord;
import com.hyfrogx.modules.manage.service.HyPayRecordService;
import com.hyfrogx.modules.manage.service.HyProductionVacuateService;
import com.hyfrogx.modules.zoom.entity.HyVipMeetConfig;
import com.hyfrogx.modules.zoom.entity.HyZoomDetail;
import com.hyfrogx.modules.zoom.entity.HyZoomMeeting;
import com.hyfrogx.modules.zoom.service.HyVipMeetConfigService;
import com.hyfrogx.modules.zoom.service.HyZoomDetailService;
import com.hyfrogx.modules.zoom.service.HyZoomMeetingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;

/**
 * @author ：Li9527
 * @date ：Created in 2019-04-04 9:27
 * @description：用户加入会议详情控制类
 * @modified By：
 * @version: 1.0
 */
@RestController
@RequestMapping("api/zoom/detail")
@Api(value = "参会议扣款及日志controller", tags = "客户端--参会扣款及日志")
public class ApiZoomDetailController {

    @Autowired
    HyZoomMeetingService meetingService;

    @Autowired
    UserService userService;

    @Autowired
    HyZoomDetailService hyZoomDetailService;

    @Autowired
    HyVipMeetConfigService vipMeetConfigService;

    @Autowired
    HyPayRecordService payRecordService;

    @Autowired
    HyProductionVacuateService hyProductionVacuateService;


    /**
     * 用户参会明细,参会离会都要调
     *
     * @param uid  参会用户uid
     * @param zoomId 会议id
     * @throws MyException
     */
    @Login
    @PostMapping("put")
    @ApiOperation("用户参会明细,参会离会都要调/判断有无支付并支付")
    public R put(@RequestParam(value = "uid", required = true) Long uid, @RequestParam(value = "zoomId", required = true) Integer zoomId) {
        try {
            // 先判断这条记录有没有已经生成
            HyZoomDetail hyZoomDetail = hyZoomDetailService.getOne(new QueryWrapper<HyZoomDetail>().eq("zoom_id", zoomId).eq("uid", uid));
            if (hyZoomDetail != null) {
                // 每次重新调这个接口都是更新最新的离开时间,客户端第一次该用户进入该会议时插入记录,后续都是更新最后离开时间
                hyZoomDetail.setLeaveTime(new Date());
                Boolean b = hyZoomDetailService.updateById(hyZoomDetail);
                if (b) {
                    return R.ok("更新成功");
                } else {
                    return R.error("更新失败");
                }
            } else {
                HyZoomMeeting zoomMeeting = meetingService.getOne(new QueryWrapper<HyZoomMeeting>().eq("zoomId", zoomId));
                if(zoomMeeting == null){
                    return  R.error("当前会议已结束或会议id不存在");
                }
                // 判断是不是参会者等于开会者
                if(zoomMeeting.getCurrentuid().equals(uid)){
                    return R.error("账号为本场会议开会者,无需扣除系统参会收费及门票");
                }
                HyZoomDetail newDetail = new HyZoomDetail();
                newDetail.setUid(uid);
                newDetail.setZid(zoomMeeting.getId());
                newDetail.setZoomId(zoomId);
                newDetail.setCreateTime(new Date());
                // 付款逻辑 第一步：从系统扣参会费用开始/区分普通及专属 体验需要略过
                if (zoomMeeting.getIsvipzoom() == 1) {
                    // 专属参会价格
                    HyVipMeetConfig hyVipMeetConfig = vipMeetConfigService.getOne(new QueryWrapper<HyVipMeetConfig>().eq("capacity", zoomMeeting.getMeetingcapacity()));
                    // 收费大于0并且不是开会者
                    if (Integer.valueOf(hyVipMeetConfig.getPrice()) > 0 && !zoomMeeting.getCurrentuid().equals(uid)) {
                        userService.reduce(uid, hyVipMeetConfig.getPrice());
                    }
                }
                if (zoomMeeting.getIsvipzoom() == 0) {
                    int needPay = meetingService.getJoinBasicMeetNeedpay(zoomMeeting);
                    if (needPay > 0 ) {
                        userService.reduce(uid, needPay);
                        this.costSystemOrder(uid, zoomMeeting.getZoomid(), needPay);
                    }
                }
                // 第二重，会议门票扣除金额,只有收费金额大于零的情况下
                if (zoomMeeting.getPrice() > 0) {
                    userService.reduce(uid, zoomMeeting.getPrice());
                    // 植入提成功能
                    this.costUserOrder(uid, zoomMeeting);
                }
                Boolean b = hyZoomDetailService.save(newDetail);
                if (b) {
                    return R.ok("参会扣费成功");
                } else {
                    return R.error("参会扣费失败");
                }
            }
        } catch (MyException e) {
            return R.error(e.getMessage());
        }
    }


    public int costSystemOrder(Long uid, Integer zoomid, Integer price) {
        // TODO Auto-generated method stub
        // 生成订单
        HyPayRecord payRecord = new HyPayRecord();
        payRecord.setCreatedate(new Date());
        payRecord.setTotal(price);
        payRecord.setMoney(0);
        payRecord.setNum(0);
        payRecord.setType(PayType.join_meet_system_charge.getCode());
        payRecord.setPercentCoin(0);
        payRecord.setPercent(0f);
        payRecord.setYid(FrogConstant.admin_uid);
        // 扣费者id
        payRecord.setUid(uid);
        // 资源对应id(本次为抽取无资源)
        payRecord.setSid(zoomid);
        payRecordService.save(payRecord);
        return 1;
    }

    public int costUserOrder(Long uid, HyZoomMeeting meeting) {
        // 生成扣费订单
        HyPayRecord payRecord = new HyPayRecord();
        payRecord.setCreatedate(new Date());
        int true_price = meeting.getPrice();
        if(meeting.getIsvipzoom() != 1){
            // 获取普通会议参会抽成基数及比例
            HyProductionScaleEntity comenScale = hyProductionVacuateService.getOne(new QueryWrapper<HyProductionScaleEntity>().eq("param_key",FrogConstant.SysConfigKey.COMMEN_MEET_CARD));
            payRecord.setPercentBaseCoin(comenScale.getBasePrice().intValue());
            if (meeting.getPrice() >= comenScale.getBasePrice().intValue()) {
                true_price = (int) Math.floor((double) meeting.getPrice() * (100 - comenScale.getScale()) / 100);
                payRecord.setPercent((float) comenScale.getScale() / 100);
                payRecord.setPercentCoin(meeting.getPrice() - true_price);
            }
        }else{
            // 获取专属会议参会抽成基数及比例
            HyProductionScaleEntity vipScale = hyProductionVacuateService.getOne(new QueryWrapper<HyProductionScaleEntity>().eq("param_key",FrogConstant.SysConfigKey.VIP_MEET_CARD));
            payRecord.setPercentBaseCoin(vipScale.getBasePrice().intValue());
            if (meeting.getPrice() >= vipScale.getBasePrice().intValue()) {
                true_price = (int) Math.floor((double) meeting.getPrice() * (100 - vipScale.getScale()) / 100);
                payRecord.setPercent((float) vipScale.getScale() / 100);
                payRecord.setPercentCoin(meeting.getPrice() - true_price);
            }
        }
        // 扣款成功后,开会者增加余额
        userService.addBean(meeting.getCurrentuid(), true_price);
        payRecord.setTotal(meeting.getPrice());
        payRecord.setMoney(0);
        payRecord.setNum(0);
        payRecord.setType(PayType.zoom_join_pay.getCode());
        // 收费者id
        payRecord.setYid(meeting.getCurrentuid());
        // 扣费者id
        payRecord.setUid(uid);
        // 会议室id
        payRecord.setSid(meeting.getZoomid());
        payRecordService.save(payRecord);
        return 1;
    }

}
